import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { PrismaClient } from '@prisma/client';
import { ApiResponse } from '../utils/response';

const prisma = new PrismaClient();
const JWT_SECRET = process.env.JWT_SECRET || 'korea-financial-system-secret-key';

interface AdminJwtPayload {
  adminId?: number;
  userId?: number;
  username?: string;
  idNumber?: string;
  role: string;
  userType: 'ADMIN' | 'USER';
  isPartner?: boolean;  // 是否为合作伙伴
  partnerCode?: string;  // 合作伙伴邀请码
}

// 管理员认证中间件（支持管理员和推荐人）
export const adminAuthMiddleware = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const authHeader = req.headers.authorization;

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      res.status(401).json(ApiResponse.error('인증 토큰이 제공되지 않았습니다.'));
      return;
    }

    const token = authHeader.substring(7);

    try {
      const decoded = jwt.verify(token, JWT_SECRET) as AdminJwtPayload;

      // 根据userType判断是管理员还是普通用户
      if (decoded.userType === 'ADMIN' && decoded.adminId) {
        // 验证管理员是否存在且状态正常
        const admin = await prisma.admin.findUnique({
          where: {
            id: decoded.adminId,
            status: 'ACTIVE'
          }
        });

        if (!admin) {
          res.status(401).json(ApiResponse.error('관리자 계정이 없거나 비활성화되었습니다.'));
          return;
        }

        // 将管理员信息添加到请求对象
        (req as any).adminId = admin.id;
        (req as any).adminUsername = admin.username;
        (req as any).adminRole = admin.role;
        (req as any).adminName = admin.name;
        (req as any).userType = 'ADMIN';
        (req as any).isPartner = admin.isPartner;
        (req as any).partnerCode = admin.partnerCode;
      } else if (decoded.userType === 'USER' && decoded.userId) {
        // 验证普通用户是否存在且状态正常
        const user = await prisma.user.findUnique({
          where: {
            id: decoded.userId,
            status: 'ACTIVE'
          }
        });

        if (!user) {
          res.status(401).json(ApiResponse.error('사용자 계정이 없거나 비활성화되었습니다.'));
          return;
        }

        // 将用户信息添加到请求对象（作为推荐人角色）
        (req as any).userId = user.id;
        (req as any).adminUsername = user.username;
        (req as any).adminRole = 'REFERRER';  // 推荐人角色
        (req as any).adminName = user.name;
        (req as any).userType = 'USER';
      } else {
        res.status(401).json(ApiResponse.error('유효하지 않은 인증 토큰입니다.'));
        return;
      }

      next();
    } catch (jwtError) {
      res.status(401).json(ApiResponse.error('유효하지 않은 인증 토큰입니다.'));
      return;
    }
  } catch (error) {
    console.error('인증 미들웨어 오류:', error);
    res.status(500).json(ApiResponse.error('인증 검증에 실패했습니다.'));
  }
};

// 角色权限检查中间件
export const requireRole = (requiredRoles: string[]) => {
  return (req: Request, res: Response, next: NextFunction) => {
    const adminRole = (req as any).adminRole;
    
    if (!adminRole || !requiredRoles.includes(adminRole)) {
      res.status(403).json(ApiResponse.error('권한이 부족합니다.'));
      return;
    }
    
    next();
  };
};

// 超级管理员权限检查
export const requireSuperAdmin = requireRole(['SUPER_ADMIN']);

// 管理员权限检查（包括超级管理员和普通管理员）
export const requireAdmin = requireRole(['SUPER_ADMIN', 'ADMIN']);

// 合作伙伴权限检查
export const requirePartner = requireRole(['PARTNER']);

// 合作伙伴和管理员权限检查
export const requirePartnerOrAdmin = requireRole(['SUPER_ADMIN', 'ADMIN', 'PARTNER']);

// 数据过滤中间件 - 合作伙伴只能查看自己邀请的用户数据
export const partnerDataFilter = (req: Request, res: Response, next: NextFunction) => {
  const adminRole = (req as any).adminRole;
  const isPartner = (req as any).isPartner;
  const adminId = (req as any).adminId;

  // 如果是合作伙伴，添加数据过滤条件
  if (isPartner && adminRole === 'PARTNER') {
    (req as any).partnerFilter = {
      partnerAdminId: adminId
    };
  }

  next();
};

export default adminAuthMiddleware;